package com.dc.www;

import java.io.IOException;
import java.net.URL;

import net.csdn.www.ImageSave;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.dc.www.util.RegexUtil;

public class CellectionData {

	public CellectionData() {
	}

	/**
	 * 刘柱栋    2013-4-22
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws Exception {
		
		String basePath = "http://album.zhenai.com/profile/getmemberdata.jsps?memberid=";
		String fileSavePath = "F://test get loveweb pics";
		for(int i = 55245410; i < 55245411; i++){
			Thread.sleep(1000);
			String path = basePath + i;
			URL url = getUrl(path);
			Document doc = Jsoup.parse(url,5000);
			System.out.println(doc);
			Elements elements = doc.getElementsByTag("img");
			Elements elementsInfo = doc.getElementsByClass("intro");
			if(elements != null){
				Element e = elements.get(1);
				String imagePath = e.attr("src");
				System.out.println(imagePath);
				imagePath = valiImageSrc(imagePath);
				if(imagePath == null){
					continue;
				}else{
					ImageSave.saveImg(imagePath, fileSavePath);
				}
			}
			
//			if(elementsInfo != null){
//				Element e = elementsInfo.get(0);
//				System.out.println(e.data());
//			}
		}
		
	}
	
	private static String valiImageSrc(String str){
		String s = null;
		String regex_1 = "http://photo\\w*.zastatic.com/";
		if(RegexUtil.vlidate(regex_1, str)){
			String regex_2 = "http://photo\\w*.zastatic.com/images/personal/default\\w*";
			if(!RegexUtil.vlidate(regex_2, str)){
				s = formatStr(str);
			}
		}
		return s;
	}
	
	private static String formatStr(String str){
		int l = str.indexOf(".jpg");
		if(l > -1){
			String s = str.substring(0, l-1);
			s += "2.jpg";
			return s;
		}else if((l = str.indexOf(".jpeg")) > -1){
			String s = str.substring(0, l-1);
			s += "2.jpeg";
			return s;
		}
		return null;
	}
	
	
	private static URL getUrl(String urlStr){
		if(!RegexUtil.vlidate("http://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))+\\.*", urlStr)){
			RuntimeException re = new IllegalArgumentException("链接不是有效的URl[the link is not effective URL link]");
			throw re;
		}
		URL url = null;
		try{
			url = new URL(urlStr);
		}catch(Exception e){
			RuntimeException re = new IllegalArgumentException("构造URL时异常[constructing the url error]");
			re.initCause(e);
			throw re;
		}
		return url;
	}

}
